<?php
declare(strict_types=1);

namespace app\apisell\command;

use app\apisell\controller\xcx\Order;
use app\apisell\controller\xcx\PopuData;
use app\apisell\service\qywx\unionService;
use app\common\miniProgram\MiniProgram;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class syncGroupsStatus extends Command
{
    protected function configure()
    {
        // 命令的名称及用途描述
        $this->setName('groupsstatus')->setDescription('更新拼团为成团');
    }
    /**
     * 执行拼团成团的操作
     * @param Input $input 输入对象，用于获取命令行输入的参数
     * @param Output $output 输出对象，用于向命令行输出信息
     */
    protected function execute(Input $input, Output $output)
    {
//        $now = date('Y-m-d H:i:s',time());
        //获取团没有满，且时间到了的数据
        try {
            $dt = date('Y-m-d H:i:s',time());
            // 补充机器人
            $resInfoList =  Db::table('xh_sell_groups')->where('grouptime', '<', time())->where('state', 1)->select()->toArray();
            //$resInfoList =  Db::table('xh_sell_groups')->where('validitytime', '<', $dt)->where('state', 1)->select()->toArray();
            if (empty($resInfoList)) {
                $output->writeln('无需自动成团');
            } else {
                Db::startTrans();  // 开始事务
                foreach ($resInfoList as $vl) {
                    $num =  $vl['people_num'] - $vl['join_num'];
                    if (empty($num)) {
                        continue;
                    }
                    $phone = Db::table('xh_sell_phone')->orderRaw('RAND()')->limit(0, $num)->select()->toArray();
                    if (empty($phone)) {
                        continue;
                    }
                    foreach ($phone as $val) {
                        $add = ['group_no'=>$vl['group_no'],'phone'=>$val['phone'],'createtime'=>date('Y-m-d H:i:s')];
                        $output->writeln('随机手机号: ' . json_encode($add, JSON_UNESCAPED_UNICODE));
                        $addSql = Db::table('xh_sell_groups_default')->insert($add);
                        $output->writeln('入库结果: ' . json_encode($addSql, JSON_UNESCAPED_UNICODE));
                    }
                    // 自动成团
                    Db::table('xh_sell_groups')->where('id', $vl['id'])->update(['state'=>4]);

                    // 发订阅消息
                    $groupTeam = Db::table('xh_sell_groups_team')
                        ->alias('a')
                        ->leftJoin('xh_sell_user u','a.user_id=u.id')
                        ->leftJoin('xh_sell_groups_order o','a.order_id=o.id')
                        ->leftJoin('xh_sell_groups_order_goods og','a.order_id=og.id')
                        ->leftJoin('xh_sell_goods g','og.goods_id=g.id')
                        ->where('a.group_no', $vl['group_no'])
                        ->field('a.*, u.openid,u.nickname,g.name as goods_name, og.actual_payment, o.order_no')
                        ->select()->toArray();
                    $template_id = env('wx.msg_template1');
                    foreach ($groupTeam as $var) {
                        $send_params = [
                            'openid' => $var['openid'],
                            'data' => [
                                'thing16' => ['value' => $var['goods_name']],
                                'amount11' => ['value' => number_format($var['actual_payment'] / 100,2)],
                                'phrase2' => ['value' => '拼团成功'],
                                'thing3' => ['value' => '恭喜您拼团成功，赶紧联系老师开课吧~']
                            ],
                            'nickname' => $var['nickname'],
                            'title' => $var['goods_name'],
                            'order_no' => $var['order_no'],
                        ];
                        MiniProgram::sendTempalteMsg($send_params,$template_id);
                    }
                }
                Db::commit();  // 提交事务
            }
            $output->writeln('批量更新拼团为成团-成功');
        } catch (\Exception $e) {
            Db::rollBack();  // 回滚事务
            $output->writeln('批量更新拼团为成团-失败Exception: ' . $e->getMessage() . '行号：' . $e->getLine() . '文件：' . $e->getTraceAsString());
        }
    }
    
    
}